import echarts from 'echarts'
import {mapState} from 'vuex'
import emsId from '@/api/emsId'
import {timerFun} from './tools'

export const emsFirstMixin = {
  data () {
    let rankRender = (h, params) => {
      let index = Number(params.index)
      let color = '#9F9C9B'
      switch (index) {
        case 0:
          color = '#43CCBA'
          break
        case 1:
          color = '#FF8915'
          break
        case 2:
          color = '#E66770'
          break
      }
      return h('div', [
        h('Icon', {
          props: {
            type: 'flag',
            size: '18'
          },
          class: 'm-iconfont',
          style: {
            'vertical-align': 'text-bottom',
            'color': color
          }
        }, ''),
        h('span', {
          style: {
            'margin-left': '7px'
          }
        }, params.row.rank)
      ])
    }
    let yearsIncrease = (h, params) => {
      let increase = params.row.increase
      increase = Number(increase.substring(0, increase.length - 1))
      let color = ''
      let className = ''
      if (increase === 0) {
        color = '#FF8915'
        className = 'md-remove'
      } else if (increase > 0) {
        color = '#43CCBA'
        className = 'md-arrow-up'
      } else {
        color = '#E66770'
        className = 'md-arrow-down'
      }
      return h('div', [
        h('span', {
          style: {
            'width': '70px',
            'display': 'inline-block'
          }
        }, params.row.increase),
        h('Icon', {
          props: {
            type: className,
            size: '18'
          },
          class: className,
          style: {
            'vertical-align': 'text-bottom',
            'color': color
          }
        }, '')
      ])
    }
    return {
      // 定时器
      timer: null,
      // 走势 是汇总还是单的
      trend: true,
      chartsUnit: '',
      // 同类对比 是汇总还是单的
      // sameType: true,
      // 同类对比 iView 表格
      sameCompareTable: {
        sameCompareColumns: [
          {
            title: '排 名',
            key: 'rank',
            align: 'center',
            width: 100,
            render: rankRender
          },
          {
            title: '对比项',
            key: 'energy',
            className: 'table-info-column',
            align: 'center',
            width: 100
          },
          {
            title: '所属工厂',
            key: 'name',
            align: 'center'
            // width: 140
            // render: useNumRender
          },
          {
            title: '总 量',
            key: 'useNum',
            align: 'center'
            // width: 200
          },
          {
            title: '涨 幅',
            key: 'increase',
            align: 'center',
            // width: 140,
            render: yearsIncrease
          }
        ],
        sameCompareData: [
          {
            energy: '',
            increase: '',
            name: '',
            rank: '',
            useNum: '',
            workshop: ''
          }
        ]
      },
      // 总/单车
      totalSingle: [
        {unit: '', lastPeriod: '+0%', type: '', useNum: 0, kpi: '+0%', oneRatioValue: 0, kpiValue: 0},
        {unit: '', lastPeriod: '+0%', type: '', useNum: 0, kpi: '+0%', oneRatioValue: 0, kpiValue: 0}
      ],
      // 走势图
      energyTrendObj: {
        title: '',
        xData: [],
        yLeft: [],
        yRight: [],
        yName: []
      },
      // 过往对比(近四年)
      pastCompareObj: {
        data: [],
        dataYear: [],
        name: ''
      },
      // 跳转二级 页面的右下角数据
      twoPageObj: {
        dev: 0,
        productionLine: 0
      }
    }
  },
  computed: {
    ...mapState('newEms', {
      navActive: state => state.navActive,
      workSpaceName: state => state.workSpaceName,
      valueList: state => state.valueList,
      activeDate: state => state.activeDate
    })
  },
  methods: {
    // 刷新 所有数据 的方法
    refreshData () {
      let params = {
        name: this.navActive,
        workSpaceName: this.workSpaceName,
        time: this.activeDate
      }
      this.post_energyTrend({...params, ...{id: emsId['energyTrend'], selectType: this.trend ? 'total' : 'single'}})
      this.post_totalSingle({...params, id: emsId['totalSingle']})
      this.post_sameCompare({...params, ...{id: emsId['sameCompare'], selectType: this.trend ? 'total' : 'single'}})
      this.post_pastCompare({...params, ...{id: emsId['pastCompare'], selectType: this.trend ? 'total' : 'single'}})
      // this.post_twoPage({...params, id: emsId['twoPage']})
    },
    // 同类对比 的 点击方法
    sameTotal (num) {
      if (num === 1) {
        if (this.trend) return false
        let params = {
          name: this.navActive,
          workSpaceName: this.workSpaceName,
          time: this.activeDate,
          selectType: 'total'
        }
        this.post_energyTrend({...params, id: emsId['energyTrend']})
        this.post_sameCompare({...params, id: emsId['sameCompare']})
        this.post_pastCompare({...params, id: emsId['pastCompare']})
        this.trend = true
      } else {
        if (this.trend) return false
        let params = {
          name: this.navActive,
          workSpaceName: this.workSpaceName,
          time: this.activeDate,
          selectType: 'total'
        }
        this.post_energyTrend({...params, id: emsId['energyTrend']})
        this.post_sameCompare({...params, id: emsId['sameCompare']})
        this.post_pastCompare({...params, id: emsId['pastCompare']})
        this.trend = true
      }
    },
    sameSingle (num) {
      if (num === 1) {
        if (!this.trend) return false
        let params = {
          name: this.navActive,
          workSpaceName: this.workSpaceName,
          time: this.activeDate,
          selectType: 'single'
        }
        this.post_energyTrend({...params, id: emsId['energyTrend']})
        this.post_sameCompare({...params, id: emsId['sameCompare']})
        this.post_pastCompare({...params, id: emsId['pastCompare']})
        this.trend = false
      } else {
        if (!this.trend) return false
        let params = {
          name: this.navActive,
          workSpaceName: this.workSpaceName,
          time: this.activeDate,
          selectType: 'single'
        }
        this.post_energyTrend({...params, id: emsId['energyTrend']})
        this.post_sameCompare({...params, id: emsId['sameCompare']})
        this.post_pastCompare({...params, id: emsId['pastCompare']})
        this.trend = false
      }
    },
    // 走势图接口
    post_energyTrend (obj = {}) {
      new window.Api(obj, 'POST').getData().then(res => {
        if (res.data.status === 200) {
          // console.log(res.data)
          this.energyTrendObj = res.data.jsData
          this.chartsUnit = res.data.jsData.unit
          // console.log(this.chartsUnit)
          this.energyTrendEcharts(this.energyTrendObj)
        }
      }).catch(function (e) {
        // console.log(e)
      })
    },
    // 总的和单车接口
    post_totalSingle (obj = {}) {
      new window.Api(obj, 'POST').getData().then(res => {
        if (res.data.status === 200) {
          if (res.data.status === 200 && res.data.jsData) {
            this.totalSingle = res.data.jsData.slice(0, 2)
          } else {
            this.totalSingle = [
              {
                kpi: '', lastPeriod: '', type: '', unit: '', useNum: ''
              },
              {
                kpi: '', lastPeriod: '', type: '', unit: '', useNum: ''
              }
            ]
          }
        }
      }).catch(function (e) {
        // console.log(e)
      })
    },
    // 同类对比接口
    post_sameCompare (obj = {}) {
      new window.Api(obj, 'POST').getData().then(res => {
        if (res.data.jsData === null) return false
        if (res.data.status === 200) {
          // console.log(res.data)
          this.sameCompareTable.sameCompareData = res.data.jsData
        }
      }).catch(function (e) {
        // console.log(e)
      })
    },
    // 过往对比(近四年)接口
    post_pastCompare (obj = {}) {
      new window.Api(obj, 'POST').getData().then(res => {
        if (res.data.status === 200) {
          this.pastCompareObj = res.data.jsData
          this.pastCompareEcharts(this.pastCompareObj)
        }
      }).catch(function (e) {
        // console.log(e)
      })
    },
    // 跳转 二级页面的 右下角的接口
    post_twoPage (obj = {}) {
      new window.Api(obj, 'POST').getData().then(res => {
        if (res.data.status === 200) {
          this.twoPageObj = res.data.jsData
        }
      }).catch(function (e) {
        // console.log(e)
      })
    },
    // 跳转下一页 的事件
    goNextPage () {
      if (this.valueList.length > 0 && this.valueList.length <= 2) {
        if (this.navActive === 'collectChart' || this.navActive === 'costPools') {
          this.$router.push({path: '/console/carbonCost'})
        } else {
          this.$router.push({path: '/console/otherEnergy'})
        }
      } else if (this.valueList.length > 2) {
        this.$router.push({path: '/console/workShop'})
      }
    },
    // 定时器封装函数
    // _timerFun (s) {
    //   let count = 0
    //   const time = () => {
    //     this.timer = setTimeout(() => {
    //       count += 3
    //       if (count > 30) {
    //         clearTimeout(this.timer)
    //         count = 0
    //       }
    //       this.refreshData()
    //       time()
    //     }, s)
    //   }
    //   time()
    // },
    // 过往对比 柱状图
    pastCompareEcharts (pastCompareObj) {
      let dom = this.$refs.kind.$refs.pastCompare
      let myChart = echarts.init(dom)
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none'
          }
        },
        grid: {
          top: '10%',
          bottom: '8%',
          right: '8%',
          left: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          // boundaryGap: false,
          boundaryGap: [0, 0.01],
          axisTick: {
            show: false
          },
          splitLine: { // 坐标轴在 grid 区域中的分隔线。
            show: true,
            lineStyle: {
              // 使用深浅的间隔色
              color: ['#8C99B6'],
              opacity: 0.1
            }
          },
          // x轴颜色
          axisLine: {
            lineStyle: {
              color: '#8C99B6',
              opacity: 0.1
            }
          },
          axisLabel: {
            color: '#8fa6e2',
            opacity: 0.1,
            margin: 10,
            formatter: (value) => {
              if (value >= 10000 && value < 10000000) {
                value = value / 10000 + '万'
              } else if (value >= 10000000 && value < 100000000) {
                value = value / 10000000 + '千万'
              } else if (value >= 100000000) {
                value = value / 100000000 + '亿'
              }
              return value
            }
          }
        },
        yAxis: {
          splitLine: { // 坐标轴在 grid 区域中的分隔线。
            show: true,
            lineStyle: {
              // 使用深浅的间隔色
              color: ['#8C99B6'],
              opacity: 0.1
            }
          },
          type: 'category',
          data: ['2016', '2017', '2018', '2019'],
          axisTick: {
            show: false
          },
          // y轴颜色
          axisLine: {
            lineStyle: {
              color: '#8C99B6',
              opacity: 0.1
            }
          },
          axisLabel: {
            color: '#8fa6e2',
            opacity: 0.1
          }
        },
        series: [
          {
            name: '',
            type: 'bar',
            data: [],
            itemStyle: {
              normal: {
                // 每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
                color: function (params) {
                  var colorList = ['#8C98AB', '#11D6A2', '#FFAD00', '#FF692F']
                  return colorList[params.dataIndex]
                },
                label: {
                  // show: true, // 开启显示
                  position: 'right', // 在上方显示
                  textStyle: { // 数值样式
                    color: function (params) {
                      var colorList = ['#8C98AB', '#11D6A2', '#FFAD00', '#FF692F']
                      return colorList[params.dataIndex]
                    },
                    fontSize: 14,
                    fontWeight: 'bold'
                  }
                }
              }
            }
          }
        ]
      }
      option.yAxis.data = pastCompareObj.dataYear
      option.series[0] = {...option.series[0], ...pastCompareObj}
      if (option && typeof option === 'object') {
        myChart.setOption(option, true)
        window.addEventListener('resize', () => {
          myChart.resize()
        })
      }
    },
    // 能耗走势 echarts 图
    energyTrendEcharts (energyTrendObj) {
      let dom = this.$refs.kind.$refs.energyTrend
      let myChart = echarts.init(dom)
      let option = {
        color: ['#11D6A2', '#FFAD00'],
        title: {
          // text: '能耗走势',
          textStyle: {
            color: 'rgba(125, 161, 255, .7)',
            fontSize: '20',
            fontWeight: 'normal'
          }
          // padding: [20, 14]
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none'
          }
        },
        grid: {
          top: '10%',
          bottom: '12%',
          left: '4%',
          right: '4%',
          containLabel: true
        },
        legend: {
          data: ['实际', '计划'],
          inactiveColor: 'rgba(153, 153, 153, 1)',
          textStyle: {
            fontSize: 14, // 字体大小
            color: '#fff'
          },
          padding: [20, 0],
          itemGap: 20, // 设置间距
          icon: 'square' // 正方形
        },
        xAxis: {
          boundaryGap: false,
          axisTick: {
            show: false
            // length: 10,
            // alignWithLabel: true,
            // lineStyle: {
            //   color: '#8C99B6'
            // }
          },
          type: 'category',
          splitLine: { // 坐标轴在 grid 区域中的分隔线。
            show: true,
            lineStyle: {
              // 使用深浅的间隔色
              color: ['#8C99B6'],
              opacity: 0.1
            }
          },
          axisLabel: {
            color: 'rgba(255, 255, 255, 0.6)',
            margin: 30
            // formatter: (value, index) => {
            //   console.log(index)
            // }
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#8C99B6',
              opacity: 0.1
            }
          },
          data: Array.from(Array(12), (v, k) => {
            if (k < 9) return '0' + (k + 1)
            return '' + (k + 1)
          })
        },
        dataZoom: [
          {
            type: 'inside'
          },
          {
            textStyle: {
              color: '#fff'
            },
            fillerColor: '#146eff',
            borderColor: '#0092fe',
            handleStyle: {
              color: '#0092fe'
            },
            height: 22
          }],
        // dataZoom: [{
        //   textStyle: {
        //     color: '#fff'
        //   }
        // }, {
        //   type: 'inside'
        // }],
        yAxis: [
          {
            name: '',
            type: 'value',
            boundaryGap: ['0%', '40%'],
            axisLabel: {
              inside: false,
              margin: 40,
              show: true,
              color: 'rgba(255, 255, 255, 0.6)',
              formatter: (value) => {
                if (value >= 10000 && value < 10000000) {
                  value = value / 10000 + '万'
                } else if (value >= 10000000 && value < 100000000) {
                  value = value / 10000000 + '千万'
                } else if (value >= 100000000) {
                  value = value / 100000000 + '亿'
                }
                return value
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#8C99B6',
                opacity: 0.1
              }
            },
            splitLine: { // 坐标轴在 grid 区域中的分隔线。
              show: true,
              lineStyle: {
                // 使用深浅的间隔色
                color: ['#8C99B6'],
                opacity: 0.1
              }
            },
            axisTick: {
              show: false
            }
          }
        ],
        series: [
          {
            name: '实际',
            type: 'line',
            data: []
          },
          {
            name: '计划',
            type: 'line',
            data: []
          }
        ]
      }
      option.xAxis.data = energyTrendObj.xData
      option.series[0].data = energyTrendObj.yLeft
      option.series[1].data = energyTrendObj.yRight
      if (option && typeof option === 'object') {
        myChart.setOption(option, true)
        window.addEventListener('resize', () => {
          myChart.resize()
        })
      }
    }
  },
  mounted () {
    this.refreshData()
    timerFun(this, 'timer', 'refreshData', 20000)
  },
  // 销毁，可以做一些定时器的销毁,缓存的清除等操作
  destroyed () {
    clearTimeout(this.timer)
  }
}
